import Vue from 'vue'
import _ from 'lodash'
import Levels from './rule-level'
import Types from './rule-type'
import Utils from './_utils'

const rule = 'equal-to'

/*
* config {
*   equalTo // Function/ComparableObject, if compare with formModel's property(eg prop1), use '${prop1}' instead
* }
* */

export default {
  priority: Levels.MEDIUM_LEVEL + 1, // validate input chars first
  validate: function (value, config, model, formModel, filed, fieldScope) {
    let errorParams = {}
    return {
      valid: Utils.validateWrapper(config.equalTo, null, value, config, model, formModel, (params, value, model, formModel) => {
        let compareWith
        if (_.startsWith(params, '${') && _.endsWith(params, '}')) {
          let compareWithFieldName = _.trimEnd(_.trimStart(params, '${'), '}')
          let compareWithField = _.chain(fieldScope).values().find(val => {
            return val.field.name === compareWithFieldName
          }).get('field').value()
          if (compareWithField) {
            compareWith = compareWithField.label || compareWithField.name
          }
          params = model[compareWithFieldName]
        } else {
          compareWith = params
        }
        Vue.set(errorParams, 'equalTo', compareWith)
        return _.isNil(value) || value === '' || value === params
      }),
      errorTemplate: undefined,
      errorParams
    }
  },
  rule: rule,
  type: Types.ATTRIBUTE
}
